<template>
  <div class="form-box">
    <!-- <h1 class="con-right-title"></h1> -->
    <h1 class="con-right-title">基本信息</h1>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="200px"
      class="demo-ruleForm"
      style="margin-bootom: 30px"
    >
      <el-form-item label="活动标题" prop="name">
        <el-input
          v-model.trim="ruleForm.name"
          :maxlength="30"
          show-word-limit
          clearable
          :disabled="isCheck"
          style="width:500px"
          @change="delRemoval"
          placeholder="请输入活动名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="活动封面" prop="cover">
        <uploadSingImg
          :imgUrl="ruleForm.cover"
          accept=".jpg,.jpeg,.png,.gif"
          :maxSize="5"
          @getImgUrl="getImgCover"
          :disabled="isCheck"
        >
          <template v-slot:imgInfo
            >（建议尺寸：750X1624 ，大小不超过5M，只可上传一张）</template
          >
        </uploadSingImg>
      </el-form-item>

      <el-form-item label="活动时间" required>
        <el-date-picker
          v-model="activityTime"
          type="datetimerange"
          size="small"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="isCheck"
          @change="handlePickerActiveTime"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="预热时间" prop="preheatTime">
        <el-date-picker
          v-model="preheatTime"
          type="datetimerange"
          size="small"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="isCheck"
          @change="handlePicker"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item prop="warmUpSetting">
        <span slot="label">
          <i v-if="preheatTime && preheatTime[0]" style="color: red">*</i>
          预热设定</span
        >
        <uploadSingImg
          :imgUrl="ruleForm.warmUpSetting"
          accept=".jpg,.jpeg,.png,.gif"
          :maxSize="5"
          @getImgUrl="getImgWarmUpCover"
          :disabled="isCheck"
        >
          <template v-slot:imgInfo
            >（建议尺寸：750X1624 ，大小不超过5M，只可上传一张）</template
          >
        </uploadSingImg>
      </el-form-item>

      <el-form-item label="是否进行分期" prop="stage">
        <el-radio-group
          v-model="ruleForm.stage"
          @change="radioChanged"
          :disabled="isCheck"
        >
          <el-radio :label="false">否</el-radio>
          <el-radio :label="true">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="榜单周期"
        prop="listPeriod"
        v-if="ruleForm.stage == true"
      >
        <el-radio-group
          class="radioGroup"
          v-model="ruleForm.listPeriod"
          :disabled="isCheck"
        >
          <el-radio
            v-for="item in listPeriodList"
            :key="item.dictValue"
            :label="item.dictValue"
            >{{ item.dictLabel }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <el-form-item label="跑马灯" prop="whetherLight">
        <el-radio-group v-model="ruleForm.whetherLight" :disabled="isCheck">
          <el-radio :label="true">开启</el-radio>
          <el-radio :label="false">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item label="作品上传要求" prop="workUpload">
        <el-radio-group v-model="ruleForm.workUpload">
          <el-radio :label="true">图文</el-radio>
          <el-radio :label="false">短视频</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-form-item label="可上传作品数" prop="publishCount">
        <el-input-number
          v-model="ruleForm.publishCount"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
      </el-form-item>

      <el-form-item>
        <span style="font-size:12px; margin-top:-10px;"
          >备注：设置 0 代表不限制上传数量</span
        >
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="ruleForm.sort"
          size="small"
          controls-position="right"
          :precision="0"
          :min="1"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
      </el-form-item>

      <div class="con-right-title">鲜花设置</div>

      <el-form-item
        label="当日赠送用户"
        prop="dayGiveNum"
        v-if="isEdit != true"
      >
        <el-input-number
          v-model="ruleForm.dayGiveNum"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
        朵
      </el-form-item>
      <el-form-item
        label="当日赠送用户"
        prop="dayGiveNum"
        v-if="isEdit == true"
      >
        <el-input-number
          v-model="ruleForm.dayGiveNum"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
        <span>朵</span>
      </el-form-item>
      <el-form-item label="用户可送鲜花数" prop="sendFlowersNum">
        <el-input-number
          v-model="ruleForm.sendFlowersNum"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
        朵
      </el-form-item>

      <el-form-item label="分享可加送" prop="shareFlowersNum">
        <el-input-number
          v-model="ruleForm.shareFlowersNum"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
        朵鲜花
      </el-form-item>

      <el-form-item label="发帖送鲜花" prop="publishFlowersNum">
        <el-input-number
          v-model="ruleForm.publishFlowersNum"
          size="small"
          controls-position="right"
          :precision="0"
          :min="0"
          :max="99999"
          :disabled="isCheck"
        ></el-input-number>
        朵鲜花
      </el-form-item>

      <el-form-item prop="description">
        <span class="con-right-title" slot="label"> 活动介绍说明 </span>
        <div class="quill-box" style="width: 100% ">
          <quill-editor
            ref="text"
            style="height: auto"
            v-model="ruleForm.description"
            class="myQuillEditor"
            :options="editorOption"
            @change="onEditorChange($event)"
            @blur="onEditorBlur($event)"
            :disabled="isCheck"
          ></quill-editor>
        </div>

        <div class="limit">
          <!-- <span>{{ nowLength }}</span> / {{ maxLen }} -->
        </div>
      </el-form-item>
    </el-form>
    <!-- form-footer -->
    <div slot="footer" class="form-footer" style="">
      <el-button type="success" @click="onSubmit" :disabled="isCheck"
        >保存</el-button
      >
      <el-button size="medium" @click="onCancel">取消</el-button>
    </div>
    <dialogUploadImg
      :dialogData="dialogUpData"
      @setImgInfo="setImgInfo"
      v-if="dialogUpData.isShow"
    ></dialogUploadImg>
  </div>
</template>

<script>
import dialogUploadImg from '@component/readManagement/readMine/dialogUploadImg' // 上传图片组件
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import '@assets/css/quill.snow.css'
import { quillEditor } from 'vue-quill-editor'
import { clearTagMixins } from '@/mixins/clearTag'
import {
  addFlowerActive,
  getVerifications,
  getActiveDetail,
  editActive
} from '@/api/flowerActive/flowerActiveList/addEdit'
export default {
  mixins: [clearTagMixins],
  components: {
    uploadSingImg,
    dialogUploadImg,
    quillEditor
  },
  data() {
    const flowersNumValidate = (rule, value, callback) => {
      if (value === 0) {
        callback(new Error('您没有填写用户可送鲜花数'))
      } else {
        callback()
      }
    }

    return {
      title: '',
      isAdd: true, //是否新增
      isCheck: false, //是否查看
      isEdit: false, //是否编辑
      activityTime: [], //活动时间
      preheatTime: [], //预热时间
      // 表单参数
      ruleForm: {
        id: '', //活动id
        name: '', //活动名称
        cover: '', // 活动封面
        activityStartTime: '', //鲜花活动开始时间
        activityEndTime: '',
        warmStartTime: '', // 鲜花活动预热结束时间
        warmEndTime: '', // 鲜花活动预热开始时间
        warmUpSetting: '', // 预热设定
        stage: false, // 鲜花活动是否分期
        listPeriod: true, // 榜单周期,
        whetherLight: true, // 是否开启跑马灯
        workUpload: true, //
        publishCount: '', //可上传作品数
        sort: 0, //排序
        dayGiveNum: 0, // 当日赠送用户
        sendFlowersNum: 0, // 用户可送鲜花数
        shareFlowersNum: 0, // 分享可加送鲜花数
        publishFlowersNum: 0, // 发帖送鲜花数
        description: '' // 活动描述
      },

      // 富文本参数
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ header: 1 }, { header: 2 }],
              [{ list: 'ordered' }, { list: 'bullet' }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ['image']
            ],
            handlers: {
              image: (value) => {
                if (value) {
                  // 在这里编写图片按钮点击操作
                  let quill = this.$refs.text.quill
                  this.editorIndex = quill.getSelection()
                    ? quill.getSelection().index
                    : 0
                  this.dialogUpData.isShow = true
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          },
          clipboard: {
            matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]]
          }
        },
        placeholder: '请输入正文'
      },
      dialogUpData: {
        isShow: false
      },
      // 富文本编辑

      textContent: '',
      nowLength: 0,
      maxLen: 500,
      overText: false, //富文本字数是否超过500
      // 榜单周期
      listPeriodList: [
        { dictLabel: '按周（周一开始）', dictValue: 'WEEK' },
        { dictLabel: '按月（1号开始）', dictValue: 'MONTH' }
      ],
      // 表单校验
      rules: {
        name: {
          required: true,
          message: '您没有填写活动标题',
          trigger: 'blur'
        },
        cover: [
          { required: true, message: '您没有上传活动封面', trigger: 'blur' }
        ],
        stage: [
          { required: true, message: '是否进行分期不能为空', trigger: 'blur' }
        ],
        listPeriod: [
          { required: true, message: '榜单周期不能为空', trigger: 'blur' }
        ],
        whetherLight: [
          { required: true, message: '跑马灯不能为空', trigger: 'blur' }
        ],
        workUpload: [
          { required: true, message: '作品上传要求不能为空', trigger: 'blur' }
        ],
        sendFlowersNum: [
          {
            required: true,
            validator: flowersNumValidate,
            // message: '您没有填写用户可送鲜花数',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    switch (this.$route.query.type) {
      case 'add':
        this.isAdd = true
        break
      case 'edit':
        this.getActiveDetail(this.$route.query.id)
        this.isEdit = true
        break
      case 'examine':
        this.getActiveDetail(this.$route.query.id)
        this.isCheck = true
        break
      default:
        break
    }
    
  },
  methods: {
    // 编辑活动
    getActiveDetail(id) {
      getActiveDetail(id, (res) => {
        if (res) {
          this.ruleForm = res
          this.activityTime = []
          this.preheatTime = []
          this.activityTime[0] = res.activityStartTime
          this.activityTime[1] = res.activityEndTime
          if (res.warmStartTime && res.warmEndTime) {
            this.preheatTime[0] = res.warmStartTime
            this.preheatTime[1] = res.warmEndTime
          }
          this.$set(this.ruleForm, 'stage', res.stageStatus)
          // 榜单周期
          this.$set(this.ruleForm, 'listPeriod', res.stagedPeriod)
        }
      })
    },
    // 活动名称去重
    delRemoval(val) {
      getVerifications(val, (res) => {
        if (res) {
          this.$message.error('活动名称重复!!!请重新填写或修改')
        }
      })
    },
    // 活动封面
    getImgCover(url) {
      this.ruleForm.cover = url
    },
    //图片插入富文本编辑器
    setImgInfo(ary) {
      // 获取富文本组件实例
      let quill = this.$refs.text.quill
      if (ary) {
        // 插入图片，res为服务器返回的图片链接地址
        for (let item of ary) {
          quill.insertEmbed(this.editorIndex++, 'image', item.url)
        }
        // 调整光标到最后
        quill.setSelection(this.editorIndex)
      }
    },

    handlePickerActiveTime() {
      this.preheatTime = []
      this.ruleForm.warmUpSetting = ''
    },

    // 选择预热时间，先要选择活动时间
    handlePicker() {
      if (this.activityTime && !this.activityTime.length) {
        this.$message.info('请先选择活动时间！')
        this.preheatTime = []
        return
      }

      if (
        this.activityTime &&
        this.activityTime.length &&
        this.preheatTime &&
        this.preheatTime.length
      ) {
        let end = this.preheatTime[1].replace(/-/g, '/')
        let start = this.activityTime[0].replace(/-/g, '/')
        let timestamp = new Date(end).getTime()
        let timestamp2 = new Date(start).getTime()
        if (timestamp >= timestamp2) {
          this.$message.info('预热时间不能晚于活动开始时间')
          this.preheatTime = []
          return
        }
      }
    },

    // 预热设定
    getImgWarmUpCover(url) {
      this.ruleForm.warmUpSetting = url
    },

    // 分期切换 清空榜单周期的值
    radioChanged(val) {
      if (val == false) {
        this.$set(this.ruleForm, 'listPeriod', '')
      }else{
        this.$set(this.ruleForm, 'listPeriod', 'WEEK')
      }
    },
    /*文字、图片等，从别处复制而来，清除自带样式，转为纯文本*/
    handleCustomMatcher(node, Delta) {
      if (this.clearStyle) {
        let ops = []
        Delta.ops.forEach((op) => {
          if (op.insert && typeof op.insert === 'string') {
            ops.push({
              insert: op.insert
            })
          }
        })
        Delta.ops = ops
        return Delta
      } else {
        return Delta
      }
    },
    // 富文本Change功能
    onEditorChange(event) {
      // let value = event.quill.getText()
      // this.textContent = value.slice(0, -1)
      // if (this.ruleForm.description === '') {
      //   this.nowLength = 0
      // } else {
      //   this.nowLength = value.length - 1
      // }
      // this.overText = this.nowLength > this.maxLen ? true : false
      // if (this.overText) {
      //   this.$message.warning(`文章内容不超过${this.maxLen}字`)
      // }
    },
    // 富文本Blur功能
    onEditorBlur(event) {},
    // 提交功能
    onSubmit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (this.preheatTime && this.preheatTime.length > 1) {
          if (!this.ruleForm.warmUpSetting) {
            this.$message.error('预热设定图片不能为空')
            return false
          }
        }

        if (!valid) {
          this.$message.warning('请检查必填项')
        } else {
          if (!this.activityTime) {
            this.$message.error('请填写活动时间')
            return false
          }

          this.$set(this.ruleForm, 'activityStartTime', this.activityTime[0])
          this.$set(this.ruleForm, 'activityEndTime', this.activityTime[1])

          if (this.preheatTime) {
            this.$set(this.ruleForm, 'warmStartTime', this.preheatTime[0])
            this.$set(this.ruleForm, 'warmEndTime', this.preheatTime[1])
          }
          // if (!this.ruleForm.stage) {
          //   if (this.ruleForm.listPeriod === '') {
          //     this.$set(this.ruleForm, 'listPeriod', 'WEEK')
          //   }
          // } 
          if (this.ruleForm.id === '') {
            // 新增
            addFlowerActive(this.ruleForm, (res) => {
              this.clearTag()
              this.$router.push({
                path: '/flowerActive/flowerActiveList/index'
              })
            })
          } else {
            editActive(this.$route.query.id, this.ruleForm, (res) => {
              this.clearTag()
              this.$router.push({
                path: '/flowerActive/flowerActiveList/index'
              })
            })
          }
        }
      })
    },
    onCancel() {
      this.clearTag()
    },
    signOut() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.form-box {
  margin: 20px 20px;
  padding: 20px 20px;
}
.quill-box {
  margin-bottom: 30px;
}

.quill-editor {
  .ql-container {
    height: calc(100vh - 162px);
    .ql-editor {
      height: calc(~'100% - 30px');
    }
  }
}
.limit {
  height: 30px;
  line-height: 30px;
  text-align: right;
  margin: 20px 0 10px;
  padding-right: 10px;
  span {
    color: #f00;
  }
}
// 保存取消的样式
.form-footer {
  width: 200px;
  margin: 0 auto;
  margin-top: 76px;
  margin-bottom: 20px;
}
</style>
